//
//  sendMessageViewController.m
//  YuErmuYing
//
//  Created by Tiancheng on 16/9/3.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "sendMessageViewController.h"
#import "xinShengErHuLiViewController.h"
#import "zhuanJiaJiangTang.h"
#import "nextDetailZhuanJiaViewController.h"
#import "HttpRequest.h"
#import "Macros.h"
#import "AFNetworking.h"
#import "TCLYUser.h"

//发布图片引用的头文件
//#import "TCLYCommunityModel.h"

@interface sendMessageViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *headerView;
//textField
@property (weak, nonatomic) IBOutlet UITextField *textField;
//textView
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *label;
//
@property (weak, nonatomic) IBOutlet UITextField *priceTextField;
@property(nonatomic,copy)NSMutableDictionary*json_Array;
@property(nonatomic,retain)UIImageView *pictureImageView01;
@property(nonatomic,retain)UIImageView *pictureImageView02;
@property(nonatomic,retain)UIImageView *pictureImageView03;
@property(nonatomic,assign)int number;
@property(nonatomic,copy)NSMutableArray *picArray;
//接收base64编码的字符串
@property(nonatomic,copy)NSString *picString;
@property(nonatomic,assign)float isTrue;
//@property (nonatomic, strong) TCLYCommunityModel * communityModel;
@end

@implementation sendMessageViewController
@synthesize json_Array,picArray;
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=YES;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isTrue=0;
    picArray=[NSMutableArray array];
    self.headerView.backgroundColor=[UIColor colorWithRed:244/255.0 green:143/255.0 blue:177/255.0 alpha:1.0];
    self.label.hidden=NO;
    //添加手势
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer  alloc ] initWithTarget:self action : @selector (onClick:)];
    self.label.userInteractionEnabled = YES;
    [self.label addGestureRecognizer:tap];
    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer  alloc ] initWithTarget:self action : @selector (onClick000:)];
    self.textView.tag=2;
    self.textView.userInteractionEnabled = YES;
    [self.textView addGestureRecognizer:tap1];
    float pictureImageView_y=self.textView.frame.origin.y+self.textView.frame.size.height+10;
    self.pictureImageView01=[[UIImageView alloc]initWithFrame:CGRectMake(12, pictureImageView_y, 0.14667*screenWidth, 0.19467*screenWidth)];
    self.pictureImageView01.image=[UIImage imageNamed:@"pull"];
    self.pictureImageView02=[[UIImageView alloc]initWithFrame:CGRectMake(12+(0.14667*screenWidth+20), pictureImageView_y, 0.14667*screenWidth, 0.19467*screenWidth)];
    self.pictureImageView02.image=[UIImage imageNamed:@"pull"];
    self.pictureImageView03=[[UIImageView alloc]initWithFrame:CGRectMake(12+(0.14667*screenWidth+20)*2, pictureImageView_y, 0.14667*screenWidth, 0.19467*screenWidth)];
    self.pictureImageView03.image=[UIImage imageNamed:@"pull"];
    [self.view addSubview:self.pictureImageView01];
    [self.view addSubview:self.pictureImageView02];
    [self.view addSubview:self.pictureImageView03];

    UITapGestureRecognizer*tap01=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onChangeImage01)];
    self.pictureImageView01.userInteractionEnabled=YES;
    [self.pictureImageView01 addGestureRecognizer:tap01];
    
    UITapGestureRecognizer *tap02=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onChangeImage02)];
    self.pictureImageView02.userInteractionEnabled=YES;
    [self.pictureImageView02 addGestureRecognizer:tap02];
    
    UITapGestureRecognizer *tap03=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onChangeImage03)];
    self.pictureImageView03.userInteractionEnabled=YES;
    [self.pictureImageView03 addGestureRecognizer:tap03];
}
-(void)onChangeImage01
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        self.number=1;
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"从手机相册选择" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                 {
                                     [self addPhotoImage];
                                 }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
-(void)onChangeImage02
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        self.number=2;
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"从手机相册选择" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                 {
                                     [self addPhotoImage];
                                 }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
//    else {
//        UIAlertView *alert = [[UIAlertView alloc]
//                              initWithTitle:@"访问图片库错误"
//                              message:@""
//                              delegate:nil
//                              cancelButtonTitle:@"OK!"
//                              otherButtonTitles:nil];
//        [alert show];
//    }
}
-(void)onChangeImage03
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        self.number=3;
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"从手机相册选择" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                 {
                                     [self addPhotoImage];
                                 }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
//    else
//    {
//        UIAlertView *alert = [[UIAlertView alloc]
//                              initWithTitle:@"访问图片库错误"
//                              message:@""
//                              delegate:nil
//                              cancelButtonTitle:@"OK!"
//                              otherButtonTitles:nil];
//        [alert show];
//    }
}
-(void)addPhotoImage
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark -- <UIImagePickerControllerDelegate>--
// 获取图片后的操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.number==1)
    {
        self.pictureImageView01.image = info[UIImagePickerControllerOriginalImage];
        self.isTrue=1;
    }
    else if (self.number==2)
    {
        self.pictureImageView02.image = info[UIImagePickerControllerOriginalImage];
        self.isTrue=1;
    }
    else if (self.number==3)
    {
        self.pictureImageView03.image = info[UIImagePickerControllerOriginalImage];
        self.isTrue=1;
    }
    // 设置图片
//    self.imageView.image = 
}

-(void)onClick:(UITapGestureRecognizer*)sender
{
    self.label.hidden=YES;
    [self.textView becomeFirstResponder];
}
-(void)onClick000:(UITapGestureRecognizer*)sender
{
    if (sender.view.tag==2)
    {
        self.label.hidden=YES;
        [self.textView becomeFirstResponder];
    }
}
//返回
- (IBAction)goBack:(id)sender
{
    zhuanJiaJiangTang *zjjt=[zhuanJiaJiangTang shardeManager];
    if (zjjt.isFirstOrNot==1)
    {
        xinShengErHuLiViewController *xselvc=self.navigationController.viewControllers[1];
        [self.navigationController popToViewController:xselvc animated:YES];
    }
}
//发布
- (IBAction)sendMessage:(id)sender
{
    if (self.isTrue==1)
    {
        if (self.number==1)
        {
            [picArray addObject:self.pictureImageView01.image];
        }
        else if (self.number==2)
        {
            [picArray addObject:self.pictureImageView01.image];
            [picArray addObject:self.pictureImageView02.image];
        }
        else if (self.number==3)
        {
            [picArray addObject:self.pictureImageView01.image];
            [picArray addObject:self.pictureImageView02.image];
            [picArray addObject:self.pictureImageView03.image];
        }
//        NSLog(@"picArray.count=%ld",picArray.count);
        [self sendDataFromNet01];
        if (picArray.count>0)
        {
            for (UIImage *image in picArray)
            {
                self.picString=[self UIImageToBase64Str:image];
                [self updateDataFromNet:self.picString];
            }
            NSLog(@"图片发布完成");
        }
    }else{
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"请选择要发布的照片" message:nil preferredStyle:UIAlertControllerStyleAlert];            UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                                                                                                                                                                                 {
                                                                                                                                                                                                     nil;
                                                                                                                                                                                                 }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    }
//网服务器发布帖子
-(void)sendDataFromNet01
{
    NSString*urlString=[NSString stringWithFormat:@"http://112.74.114.1/Parenting/index.php/api/note/publish_note"];
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    parameters[@"uid"]=userID;
    parameters[@"name"]=self.textField.text;
    parameters[@"describle"]=self.textView.text;
    parameters[@"price"]=self.priceTextField.text;
    HttpRequest *httpRequest=[HttpRequest sharedInstance];
    [httpRequest postWithURLString:urlString parameters:parameters success:^(id responseObject)
     {
         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         int msg=[[json objectForKey:@"msg"]intValue];
         if (msg==200)
         {
             NSLog(@"发布帖子成功");
         }
     } failure:^(NSError *error) {
         NSLog(@"error=%@",error);
     }];
}
//图片转字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 0.1f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}
-(void)updateDataFromNet:(NSString*)imageString
{
    NSString *urlString=[NSString stringWithFormat:@"http://112.74.114.1/Parenting/index.php/api/note/publish_note_pic"];
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    parameters[@"uid"]=userID;
    parameters[@"name"]=self.textField.text;
    parameters[@"image"]=imageString;
    //    NSLog(@"imageString=%@",imageString);
    HttpRequest *httpRequest=[HttpRequest sharedInstance];
    [httpRequest postWithURLString:urlString parameters:parameters success:^(id responseObject)
     {
         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         //获取数组
         NSLog(@"json=%@",json);
     } failure:^(NSError *error) {
         NSLog(@"error=%@",error);
     }];
}

//上传图片的接口
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
